package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class StatementItemServiceImpl implements IStatementItemService {

    @Autowired
    private StatementItemMapper statementItemMapper;

    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Autowired
    private StatementMapper statementMapper;

    @Override
    public TablePageInfo<StatementItem> selectByStatementId(StatementItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<StatementItem>(statementItemMapper.selectAllSaleOnList(qo));
    }

    @Override
    @Transactional
    public void saveItems(List<StatementItem> items) {
        //删除并获取到最后一条记录
        StatementItem item = items.remove(items.size() - 1);
        //获取优惠价格
        BigDecimal itemPrice = item.getItemPrice();
        //获取到结算单的id
        Long statementId = item.getStatementId();
        //通过结算单id查询结算单的状态
        Statement statement = statementMapper.selectByStatementId(statementId);
        //结算单处于消费中的才能保存
        if (Statement.STATUS_PAID.equals(statement.getStatus())) {
            throw new BusinessException("只有处于消费中才能保存明细");
        }
        //把明细项的集合删除掉
        statementItemMapper.deleteByPrimaryKey(statementId);

        //定义总金额,总数量
        BigDecimal totalAmount = new BigDecimal("0.00");
        BigDecimal totalQuantity= new BigDecimal("0");
        for (StatementItem statementItem : items) {
            //插入到表里
            statementItemMapper.insert(statementItem);
            totalAmount = totalAmount.add(statementItem.getItemPrice().multiply(statementItem.getItemQuantity()));
            totalQuantity = totalQuantity.add(statementItem.getItemQuantity());
        }
        if (totalAmount.compareTo(itemPrice) <0){
            throw new BusinessException("优惠价格不能大于总金额");
        }
        //更新结算单表里的数据
        statementMapper.updateAmount(statementId,totalAmount,totalQuantity,itemPrice);
    }

    @Override
    public void delete(Long id) {
        statementItemMapper.deleteByPrimaryKey(id);
    }
}
